/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.front.voucher;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.front.voucher.VoucherService;
import shop.services.front.voucher.bean.Voucher;
import shop.services.front.voucherconvert.VoucherconvertService;
import shop.services.front.voucherconvert.bean.Voucherconvert;
import shop.services.front.voucherhave.VoucherhaveService;
import shop.services.front.voucherhave.bean.Voucherhave;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**   
 * @类名称：VoucherController
 * @创建人：Wzl
 * @创建时间：2018-01-03 下午16:55:48      
 * @版本号：1.0
 * @描述：     
 */
@Controller
@RequestMapping("/front/voucher/")
public class VoucherController extends FrontBaseController<Voucher> {
    private final  static  String USER_ROLE_MANAGE_ADMIN="1";
    private final  static  String USER_ROLE_FRONT_PARTNER="2";
    private final  static  String USER_ROLE_FRONT_MEMBER="3";
    private final  static  String USER_ROLE_FRONT_COMMON="4";
    @Resource
    private VoucherService voucherService;
    @Resource
    private VoucherconvertService voucherconvertService;
    @Resource
    private UserService userService;
    @Resource
    private VoucherhaveService voucherhaveService;
    @Override
    public Services<Voucher> getService() {
        return voucherService;
    }

    /**
     * 跳转到积分商城页面（礼卷列表）
     *
     * @return
     */
    @RequestMapping("toShopList")
    public String toShopList() {
        return "/front/scoreShop/shopList";
    }

    /**
     * 跳转到兑换礼卷页面（礼卷详情）
     *
     * @return
     */
    @RequestMapping("toExchange")
    public String toExchange() {
        return "/front/scoreShop/exchange";
    }

    /**
     * 跳转到礼卷列表页面
     *
     * @return
     */
    @RequestMapping("toVoucherList")
    public String toVoucherList() {
        return "/front/voucher/voucherList";
    }

    /**
     * 跳转到选择礼卷页面
     *
     * @return
     */
    @RequestMapping("toChooseVoucher")
    public String toChooseVoucher() {
        return "/front/voucher/selectVoucher";
    }

    /**
     * 跳转到生成礼卷页面
     *
     * @return
     */
    @RequestMapping("toSetVoucher")
    public String toSetVoucher() {
        return "/front/voucher/setVoucher";
    }

    /**
     * 跳转到生成充值优惠礼卷页面
     *
     * @return
     */
    @RequestMapping("toSetCashVoucher")
    public String toSetCashVoucher() {
        return "/front/voucher/setCashVoucher";
    }

    /**
     * 跳转到领取礼卷页面
     *
     * @return
     */
    @RequestMapping("toGetVoucher")
    public ModelAndView toGetVoucher(HttpServletRequest request) {
        logger.debug("领取礼卷页面跳转: "+request.getRequestURI()+"?"+request.getQueryString());
        User user=(User)request.getSession().getAttribute("userInfo");
        if(!StringUtils.isBlank(request.getQueryString())){
            String []ids=request.getQueryString().split("_");
            if(ids.length==2&&"0".equals(user.getPid())){
                user.setPid(ids[1]);
                user.setRid(USER_ROLE_FRONT_MEMBER);
                userService.update(user);
                request.getSession().setAttribute("userInfo", user);
                //会员加入模板消息通知
                User supUser=new User();
                supUser.setId(ids[1]);
                supUser=userService.selectOne(supUser);
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "尊敬的股东，您有新的会员加入！");
                msgParam.put("keyword1", user.getNickname());
                msgParam.put("keyword2", user.getPhone());
                msgParam.put("keyword3", user.getId());
                msgParam.put("remark", "点击查看详情");
                WxMsgUtil.sendMemberJoinMsg(msgParam, systemManager, supUser.getOpenID());
            }
        }
        ModelAndView modelAndView = new ModelAndView("/front/voucher/getVoucher");
        return modelAndView;
    }

    /**
     * 查询礼卷列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectVoucherList")
    @ResponseBody
    public JSONResult selectVoucherList(Voucher voucher){
        List<Voucher> voucherList = voucherService.selectVoucherList(voucher);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(voucherList);
        return jsonResult;
    }

    /**
     * 积分兑换礼卷
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "exchangeVoucher", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult exchangeVoucher(HttpSession session, Voucher voucher){
        User user=(User)session.getAttribute("userInfo");
        Voucherconvert voucherconvert=new Voucherconvert();
        voucherconvert.setUserID(user.getId());
        voucherconvert.setVoucherID(voucher.getId());
        voucherconvert.setAmount(1);
        voucherconvertService.insert(voucherconvert);//兑换记录
        voucher=voucherService.selectOne(voucher);
        voucher.setStock(voucher.getStock()-1);
        voucherService.update(voucher);//更新礼卷库存
        user.setScore(user.getScore().subtract(voucher.getScore()));
        userService.update(user);//更新用户积分
        Voucherhave voucherhave=new Voucherhave();
        voucherhave.setUserID(user.getId());
        voucherhave.setVoucherID(voucher.getId());
        Voucherhave voucherhaveInfo=voucherhaveService.selectOne(voucherhave);
        if(voucherhaveInfo!=null){
            voucherhaveInfo.setAmount(voucherhaveInfo.getAmount()+1);//更新用户礼卷数量
        }else{
            voucherhave.setAmount(1);
            voucherhaveService.insert(voucherhave);//更新用户礼卷数量
        }
        JSONResult jsonResult = new JSONResult();
        return jsonResult;
    }
}
